import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:factoryside/api/api.dart';
import 'package:factoryside/index.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/webview/page_web.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';


class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LoginState();
}

class LoginState extends State<Login> {
  final formKey = GlobalKey<FormState>();
  var username = '';
  var password = '';
  var code = '';
  var adminToken = '';
  bool pwdOrCode = true;//密码登录true 验证码登录false
  Timer _timer;
  var _autoCodeText;
  var _timeCount = 60;
  bool showPassword = false;
  TextEditingController userNameCon = TextEditingController();
  TextEditingController pwdCon = TextEditingController();
  TextEditingController codeCon = TextEditingController();
  TextEditingController hostCtr = TextEditingController();
  List<String> hosts = [
    'https://api.xigyu.com/api/',
    'http://192.168.0.203:8810/api/',
    'http://192.168.101.82:8810/api/',
    'http://192.168.0.95:8810/api/',
    'http://192.168.0.215:8810/api/',
    'http://192.168.0.22:8810/api/',
    '自定义地址',
  ];
  String host;

  WebViewController _webViewController;

  var _pSelected=false;
  var wxInstalled=false;
  save() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("userName", username);
    prefs.setString("pwd", password);
    prefs.setString("adminToken", adminToken);
  }
  TapGestureRecognizer _tapRecognizer_agreement;
  TapGestureRecognizer _tapRecognizer_privacy;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isWeChatInstalled.then((value){
      setState(() {
        wxInstalled=value;
      });
    });
    SharedPreferences.getInstance().then((value){
      print('第一次${value.getBool("isFirst")}');
      if(value.getBool("isFirst")==null){
        Future.delayed(Duration.zero, () {
          showPrivacy();
        });
      }
    });
    _tapRecognizer_agreement=TapGestureRecognizer();
    _tapRecognizer_privacy=TapGestureRecognizer();
    _tapRecognizer_agreement.onTap=toAgreement;
    _tapRecognizer_privacy.onTap=toPrivacy;
    username = Api.userName;
    userNameCon.text = Api.userName;
    password = Api.pwd;
    pwdCon.text = Api.pwd;
    weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is WeChatAuthResponse) {
//        setState(() {
          print("state :${res.state} \n code:${res.code}");

//        });
        if(res.state!='login'){
          return;
        }
        //或取access_token 和openid
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd22da3eb42259071&secret=dac072c98881a324665bfbaa7f7e7c76&code=" + res.code + "&grant_type=authorization_code";
        RequestUtil.getInstance()
            .get(path).then((response){
          print('微信$response');
          /**
           * access_token : ACCESS_TOKEN
           * expires_in : 7200
           * refresh_token : REFRESH_TOKEN
           * openid : OPENID
           * scope : SCOPE
           * unionid : o6_bmasdasdsad6_2sgVt7hMZOPfL
           */
          var json=jsonDecode(response.data);
          //获取微信用户信息
          String path = "https://api.weixin.qq.com/sns/userinfo?access_token=" + json['access_token'] + "&openid=" + json['openid'];
          RequestUtil.getInstance().get(path).then((response){
            /**
             * openid : oHcBn6L8tz-LD1gpkhkJuG5XnskA
             * nickname : 12580蛋炒饭
             * sex : 1
             * language : zh_CN
             * city : Shaoxing
             * province : Zhejiang
             * country : CN
             * headimgurl : http://thirdwx.qlogo.cn/mmopen/vi_32/cGOJiapw3l1wguKkJOLtSzHnFk03tWlllldMXbLMKhywtibMPIh0MHJI81CNLfyQGgzmV7X7GxiaR8uyK1V1tAE9Q/132
             * privilege : []
             * unionid : o8TpJ6H0nzdJfsZVLEzQusBd7EO8
             */
            var json=jsonDecode(response.data);
            RequestUtil.post(Api.wxRegister,{
              'openid': json['openid'],
              'nickname': json['nickname'],
              'sex': json['sex'],
              'language': json['language'],
              'city': json['city'],
              'province': json['province'],
              'country': json['country'],
              'headimgurl': json['headimgurl'],
              'unionid': json['unionid']
            }).then((value){
              if(value['Data']['code']==0){
                showToast( "登陆成功");
                username = value['Data']['data']['user']['UserName'];
                adminToken = value['Data']['data']['token'];
                Api.userName=username;
                Api.adminToken=adminToken;
                Api.isSon=value['Data']['data']['user']['ParentUserID']!=null&&value['Data']['data']['user']['ParentUserID']!='';
                save();
                push(context,Index());
              }else{
//                showToast( "未绑定手机号");
                if (mounted) {
//                  Navigator.push(context, CupertinoPageRoute(
//                                      builder: (BuildContext context) {
//                                        return BindPhonePage(json);
//                                      }));
                }
              }
            });
          });
        });
      }
    });
  }

  void showPrivacy() {
    showDialog<Null>(
      context: context,
      barrierDismissible: true,
      builder: (context) {
        return StatefulBuilder(builder: (context, state) {
          var width = MediaQuery.of(context).size.width;
          var height = MediaQuery.of(context).size.height;
          return AlertDialog(
            //                              contentPadding: EdgeInsets.all(10),
              content: Container(
                child: Column(
                  children: [
                    Expanded(
                      child: WebView(
                          onWebViewCreated: (WebViewController webViewController) {
                            _webViewController = webViewController;
                          },
                          initialUrl: 'https://admin.xigyu.com/message/userprivacy',
                          //JS执行模式 是否允许JS执行
                          javascriptMode: JavascriptMode.unrestricted
                      ),
                    ),
                    Container(
                      color: Colors.transparent,
                      width: double.infinity,
                      height: 50,
                      margin: EdgeInsets.all(10),
                      child: RaisedButton(
                        onPressed: () async {
                          SharedPreferences prefs = await SharedPreferences.getInstance();
                          prefs.setBool("isFirst", true);
                          setState(() {
                            _pSelected=!_pSelected;
                          });
                          Navigator.pop(context);
                        },
                        child: Text(
                          '我已阅读并同意',
                          style: TextStyle(color: Colors.white),
                        ),
                        color: ColorsUtil.hexToColor(Api.btnColor),
                      ),
                    )
                  ],
                ),
                width: width * 0.9,
                height: height * 0.5,
              ));
        });
      },
    );
  }


  void toAgreement(){
    push(context, WebPage('服务协议', 'https://admin.xigyu.com/Message/service', null));
  }
  void toPrivacy(){
    push(context, WebPage('隐私政策', 'https://admin.xigyu.com/message/userprivacy', null));
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('被销毁了');
    if(_timer!=null){
      _timer.cancel();
    }
    _tapRecognizer_agreement.dispose();
    _tapRecognizer_privacy.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      body: Container(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: ListView(
          children: <Widget>[
            Container(
              alignment: Alignment.bottomLeft,
              height: 120,
              child: Text(
                'Hi，欢迎使用西瓜鱼服务',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(0, 30, 0, 10),
              child: TextField(
                controller: userNameCon,
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  labelText: '请输入账号',
                ),
                onChanged: (value) {
                  this.setState(() {
                    username = value;
                  });
                },
              ),
            ),
            Visibility(
                visible: pwdOrCode,
                child: Container(
              margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
              child: TextField(
                controller: pwdCon,
                decoration: InputDecoration(
                  labelText: '请输入密码',
                  suffixIcon: GestureDetector(
                    child: Icon(Icons.remove_red_eye, color: Colors.black26),
                    onTap: () {
                      setState(() {
                        showPassword = !showPassword;
                      });
                    },
                  ),
                ),
                obscureText: !showPassword,
                onChanged: (value) {
                  this.setState(() {
                    password = value;
                  });
                },
              ),
            )),
            Container(
              height: 50.0,
              width: double.infinity,
              margin: EdgeInsets.fromLTRB(0, 40, 0, 10),
              child: RaisedButton(
                color: ColorsUtil.hexToColor(Api.btnColor),
                disabledColor: Colors.grey,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Text(
                  '登录',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    letterSpacing: 2,
                  ),
                ),
                onPressed:
                    (!isNullOrEmpty(username) && (pwdOrCode?!isNullOrEmpty(password):!isNullOrEmpty(code)))
                        ? _handleLogin
                        : null,
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
//                InkWell(
//                    onTap: (){
//                      setState(() {
//                        pwdOrCode=!pwdOrCode;
//                      });
//                    },
//                    child: Text(pwdOrCode?'验证码登录':'密码登录')),

              ],
            ),
            GestureDetector(
                onTap: (){
                  setState(() {
                    _pSelected=!_pSelected;
                  });
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 20.0,
                  width: double.infinity,
                  margin: EdgeInsets.fromLTRB(0, 20, 0, 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        _pSelected
                            ? 'assets/checked.png'
                            : 'assets/unchecked.png',
                        width: 15,
                        height: 15,
                      ),
                      SizedBox(width: 10,),
                      RichText(
                          text: TextSpan(
                              text: '请阅读并同意',
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 13
                              ),
                              children: [
                            TextSpan(
                              text: '《西瓜鱼服务协议》',
                              style: TextStyle(
                                color: Colors.blue,
                                  fontSize: 13
                              ),
                              recognizer: _tapRecognizer_agreement
                            ),
                            TextSpan(text: '和 '),
                            TextSpan(
                                text: "《隐私政策》",
                                style: TextStyle(
                                  color: Colors.blue,
                                    fontSize: 13
                                ),
                                recognizer: _tapRecognizer_privacy
                            )
                          ])),
                    ],
                  ),
                )),
            Visibility(
                visible: wxInstalled,
                child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Container(height: 0.5, color: Colors.grey),
                    ),
                    Container(
                        margin: EdgeInsets.fromLTRB(20, 0, 20, 0),
                        child: Text('第三方登录')),
                    Expanded(
                      child: Container(height: 0.5, color: Colors.grey),
                    ),
                  ],
                ),
                Container(
                  width: 60,
                  height: 60,
                  child: IconButton(
                      icon: Image.asset('assets/weixin.png',
                      ), onPressed: (){
                    sendWeChatAuth(
                        scope: "snsapi_userinfo", state: "login")
                        .then((data) {
                      if (!data) {
                        showToast('请先安装微信APP');
                      }
                      print('========$data');
                    });
                  }),
                )
              ],
            ))
          ],
        ),
      ),
    );
  }
  ///更改服务器地址
  void changeHost(){
    showDialog<Null>(
      context: context,
      barrierDismissible: true,
      builder: (context) {
        return StatefulBuilder(
            builder: (context, state) {
              return AlertDialog(
                title: Center(
                  child: Text('更改服务器地址'),
                ),
                content: Container(
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Expanded(child: DropdownButton(
                            // 隐藏下划线
                              underline: Container(
                                  height: 0),
                              hint: Text('请选择服务器地址',overflow: TextOverflow.ellipsis,),
                              value: host,
                              items: hosts
                                  .map((e) =>
                                  DropdownMenuItem(
                                      child:
                                      Text(
                                        e),
                                      value: e))
                                  .toList(),
                              onChanged: (value) {
                                print(value);
                                host = value;
                                hostCtr.text =
                                (value == '自定义地址'
                                    ? ''
                                    : value);
                                state(() {});
                              }))
                        ],
                      ),
                      Expanded(child: TextField(
                        controller: hostCtr,
                        maxLines: 5,
                        decoration: InputDecoration(
                            hintText: '请输入服务器地址',
                            contentPadding:
                            EdgeInsets.all(10),
                            border:
                            OutlineInputBorder(
                              borderRadius:
                              BorderRadius
                                  .circular(
                                  5.0),
                            )),
                      ))
                    ],
                  ),
                  height: 200,
                ),
                actions: <Widget>[
                  FlatButton(
                    child: Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  FlatButton(
                    child: Text('确定'),
                    onPressed: () {
                      var host = hostCtr.text;
                      if (host.isEmpty) {
                        showToast('请输入服务器地址');
                      } else {
                        username=username.substring(0,username.lastIndexOf('@'));
                        Dio dio=RequestUtil.getInstance();
                        dio.options.baseUrl=host;
                        Navigator.of(context).pop();
                        login();
                      }
                    },
                  ),
                ],
              );
            });
      },
    );
  }
  void hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus.unfocus();
    }
  }
  _handleLogin() async {
    hideKeyboard(context);
    if(!_pSelected){
      showToast('请阅读并同意《西瓜鱼服务协议》和《隐私政策》');
      return;
    }
    Dio dio=RequestUtil.getInstance();
    if(username.contains('@')){
      changeHost();
    }else{
      dio.options.baseUrl='https://api.xigyu.com/api/';
      login();
    }
//    login();
  }
  ///工厂账号：13967039653
  ///工厂账号：13486687955
  ///工厂账号：15867444926
  void login() {
    RequestUtil.showLoadingDialog(context);
    RequestUtil
          .post(Api.login, {
        'userName': username,
        'passWord':password,
        'RoleType':6
      }).then((value) {
      RequestUtil.hiddenLoadingDialog(context);
      if (value['Data']['code']==0) {
        showToast( "登陆成功");
        adminToken = value['Data']['data']['token'];
        String parentUserID = value['Data']['data']['user']['ParentUserID'];
        Api.userName=username;
        Api.adminToken=adminToken;
        Api.isSon=parentUserID!=null&&parentUserID!='';
        Api.pwd=password;
        save();
        Navigator.pushReplacement(this.context, CupertinoPageRoute(
            builder: (BuildContext context) {
              return Index();
            }));
      } else {
        showToast(value['Data']['msg']);
      }
    });
  }
  void _startTimer() {
    showToast( '短信验证码已发送，请注意查收');
    _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
      if(mounted){
        setState(() {
          if (_timeCount <= 0) {
            _autoCodeText = '重新获取';
            _timer.cancel();
            _timeCount = 60;
          } else {
            _timeCount -= 1;
            _autoCodeText = "$_timeCount" + 's';
          }
        });
      }
    });
  }
}
